import React, { useEffect, useState } from 'react';
import { Table, Button, Row, Dialog, MessagePlugin, Popconfirm, Tag } from 'tdesign-react';
import { deleteRoomAPI, getAllRoomListAPI } from '@/api/room.api';
import classnames from 'classnames';
import CommonStyle from '@/styles/common.module.less';
import SearchForm from './components/SearchForm';
import RoomForm from './components/RoomForm';
import { useLocation, useNavigate } from 'react-router-dom';
import qs from 'query-string';
import { RoomSearchFormValues } from './consts';

function getStringParam(param: any, defaultValue = ''): string {
  if (Array.isArray(param)) return param[0] || defaultValue;
  if (typeof param === 'string') return param;
  return defaultValue;
}
function getNumberParam(param: any, defaultValue = 1): number {
  if (Array.isArray(param)) return Number(param[0]) || defaultValue;
  if (typeof param === 'string') return Number(param) || defaultValue;
  if (typeof param === 'number') return param;
  return defaultValue;
}

const getQueryFromUrl = (search: string): RoomSearchFormValues => {
  const params = qs.parse(search);
  return {
    searchText: getStringParam(params.searchText),
    status: getStringParam(params.status),
    sortBy: getStringParam(params.sortBy, 'roomNumber'),
    sortOrder: getStringParam(params.sortOrder, 'ASC'),
    floorNumber: getStringParam(params.floorNumber),
    page: getNumberParam(params.page, 1),
    pageSize: getNumberParam(params.pageSize, 10),
  };
};

const RoomTable: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [tableData, setTableData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    total: 0,
    current: getQueryFromUrl(location.search).page || 1,
    pageSize: getQueryFromUrl(location.search).pageSize || 10,
  });
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [deleteVisible, setDeleteVisible] = useState(false);
  // 搜索/筛选/排序参数
  const [query, setQuery] = useState<RoomSearchFormValues>(getQueryFromUrl(location.search));
  const [floorList, setFloorList] = useState<string[]>([]);
  const [roomFormVisible, setRoomFormVisible] = useState(false);
  const [roomFormMode, setRoomFormMode] = useState<'add' | 'edit'>('add');
  const [roomFormData, setRoomFormData] = useState<any>(null);

  // 获取所有楼层号用于筛选
  useEffect(() => {
    getAllRoomListAPI({ page: 1, pageSize: 1000 }).then(res => {
      const floors = Array.from(new Set((res.data.data || []).map((item: any) => item.floorNumber))).filter(Boolean);
      setFloorList(floors as string[]);
    });
  }, []);

  // 监听URL变化，自动回显和查询
  useEffect(() => {
    const urlQuery = getQueryFromUrl(location.search);
    setQuery(urlQuery);
    setPagination(p => ({
      ...p,
      current: urlQuery.page || 1,
      pageSize: urlQuery.pageSize || 10,
    }));
  }, [location.search]);

  // 数据加载
  const fetchData = (customPagination = pagination, customQuery = query) => {
    setLoading(true);
    getAllRoomListAPI({
      page: customPagination.current,
      pageSize: customPagination.pageSize,
      ...customQuery,
    } as any).then(res => {
      setTableData(res.data.data || []);
      setPagination(prev => ({
        ...prev,
        total: res.data.pagination?.total || 0,
      }));
    }).finally(() => setLoading(false));
  };

  // 分页变化
  const handlePageChange = (current: number) => {
    const params = qs.stringify({ ...query, page: current, pageSize: pagination.pageSize });
    navigate({ search: params }, { replace: true });
  };

  const handlePageSizeChange = (size: number) => {
    const params = qs.stringify({ ...query, page: 1, pageSize: size });
    navigate({ search: params }, { replace: true });
  };

  // 搜索表单提交
  const handleSearch = (values: RoomSearchFormValues) => {
    // 同步到URL，重置到第一页
    const params = qs.stringify({ ...values, page: 1, pageSize: pagination.pageSize });
    navigate({ search: params }, { replace: true });
  };

  // 排序事件
  const handleSortChange = (sort: any) => {
    let newQuery = { ...query };
    if (sort && sort.length > 0) {
      newQuery = {
        ...query,
        sortBy: sort[0].sortBy,
        sortOrder: sort[0].desc ? 'DESC' : 'ASC',
      };
    } else {
      newQuery = {
        ...query,
        sortBy: 'roomNumber',
        sortOrder: 'ASC',
      };
    }
    // 同步到URL，重置到第一页
    const params = qs.stringify({ ...newQuery, page: 1, pageSize: pagination.pageSize });
    navigate({ search: params }, { replace: true });
  };

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, query]);

  // 删除操作
  const handleDelete = (id: string) => {
    deleteRoomAPI(id).then(res => {
      if (res.status === 200) {
        MessagePlugin.success(res.data.message);
        setDeleteVisible(false);
        fetchData();
      } else {
        MessagePlugin.error(res.data.message);
      }
    }).catch(err => {
      MessagePlugin.error(err.message);
    });
  };

  // 新建
  const handleAdd = () => {
    setRoomFormMode('add');
    setRoomFormData(null);
    setRoomFormVisible(true);
  };

  // 编辑
  const handleEdit = (row: any) => {
    setRoomFormMode('edit');
    setRoomFormData(row);
    setRoomFormVisible(true);
  };

  const roomColumns = [
    { title: '楼层', colKey: 'floorNumber', align: 'center', width: 80 },
    { title: '包间号', colKey: 'roomNumber', align: 'center', width: 100 },
    { title: '描述', colKey: 'description', align: 'center', width: 180 },
    {
      title: '状态', colKey: 'status', align: 'center', width: 100,
      cell: ({ row }: { row: any }) => {
        if (row.status === 'available') return <Tag theme='primary' variant='light'>可用</Tag>;
        if (row.status === 'maintenance') return <Tag theme='warning' variant='light'>维护</Tag>;
        return <Tag theme='danger' variant='light'>占用</Tag>;
      }
    },
    {
      title: '操作',
      colKey: 'op',
      align: 'center',
      width: 160,
      cell: ({ row }: { row: any }) => (
        <>
          <Button theme='primary' variant='text' onClick={() => handleEdit(row)}>
            编辑
          </Button>
          <Popconfirm theme='danger' content='确定删除当前包间？' confirmBtn='确定' cancelBtn='取消' onConfirm={() => handleDelete(row.id)}>
            <Button theme='danger' variant='text'>
              删除
            </Button>
          </Popconfirm>
        </>
      )
    }
  ];

  return (
    <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
      <Row justify='start' style={{ marginBottom: '20px' }}>
        <SearchForm
          onCancel={() => {
            setQuery({
              searchText: '',
              status: '',
              sortBy: 'roomNumber',
              sortOrder: 'ASC',
              floorNumber: '',
              page: 1,
              pageSize: pagination.pageSize,
            });
            setPagination(p => ({ ...p, current: 1 }));
            navigate({ search: '' }, { replace: true });
          }}
          onSubmit={handleSearch}
          floorList={floorList}
          onAdd={handleAdd}
        />
      </Row>
      <Table
        loading={loading}
        data={tableData}
        columns={roomColumns as any}
        rowKey='id'
        pagination={{
          total: pagination.total,
          current: pagination.current,
          pageSize: pagination.pageSize,
          showJumper: true,
          onCurrentChange: handlePageChange,
          onPageSizeChange: handlePageSizeChange,
        }}
        sort={query.sortBy ? [{ sortBy: query.sortBy, descending: query.sortOrder === 'DESC' }] : undefined}
        onSortChange={handleSortChange}
      />
      <RoomForm
        visible={roomFormVisible}
        mode={roomFormMode}
        roomData={roomFormData}
        onClose={() => setRoomFormVisible(false)}
        onSuccess={fetchData}
      />
      <Dialog
        header='确认删除当前包间？'
        visible={deleteVisible}
        onClose={() => setDeleteVisible(false)}
        onConfirm={() => deleteId && handleDelete(deleteId)}
        destroyOnClose
      >
        <p>删除后该包间信息将被清空，且无法恢复。</p>
      </Dialog>
    </div>
  );
};

export default RoomTable;

